package com.myfojing.mycloud;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ConfigWifiFragment extends Fragment {

    Button btnListAP;
    Button btnSaveWifi;

    private String ip;
    private String port;
    private Sensirion sensirion;
    private OnFragmentInteractionListener mListener;
    private ListView listView;

    private ArrayList<HashMap<String, String>> list;
    private WifiCacheListviewAdapter adapter;
    // ui
    private TextView txt_ssid;
    private TextView txt_passwd;
    private Handler handler;
    private int mPosition;

    public ConfigWifiFragment() {
        // Required empty public constructor
    }

    public static ConfigWifiFragment newInstance(String ip, String port) {
        ConfigWifiFragment fragment = new ConfigWifiFragment();
        Bundle args = new Bundle();
        args.putString("ip_config", ip);
        args.putString("port_config", port);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ip = getArguments().getString("ip_config");
            port = getArguments().getString("port_config");
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_config_wifi, container, false);
        // ui
        txt_ssid = (TextView) view.findViewById(R.id.txt_ssid);
        txt_passwd = (TextView) view.findViewById(R.id.txt_passwd);
        listView = (ListView) view.findViewById(R.id.config_wifi_listview);

        btnListAP = (Button) view.findViewById(R.id.btnListAP);
        btnListAP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onListAPClick(v);
            }
        });

        btnSaveWifi = (Button) view.findViewById(R.id.btnSaveWifi);
        btnSaveWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sensirion.write_wifi(txt_ssid.getText().toString(), txt_passwd.getText().toString());
            }
        });

        handler = new Handler();
        // list view: wifi cache
        list = new ArrayList<>();
        adapter = new WifiCacheListviewAdapter(getActivity(), list);
        listView.addHeaderView(View.inflate(getContext(), R.layout.wifi_cache_listview_header, null));
        listView.setAdapter(adapter);

        sensirion = new Sensirion(ip, port);
        sensirion.setSensirionListener(new Sensirion.SensirionListener() {
            @Override
            public void onDataReady(JSONObject data) {
                try {
                    String cmd = data.getString("cmd");
                    // 读取wifi缓存
                    if (cmd.equals("read_wifi")) {
                        if (data.getBoolean("success")) {
                            Integer index_of_ap = data.getInt("index_of_ap");
                            adapter.setApIndex(index_of_ap);
                            // 加入list
                            int qty = data.getInt("qty");
                            for (Integer i = 1; i <= qty; i++) {
                                JSONObject ap = data.getJSONObject(i.toString());
                                HashMap<String, String> map = new HashMap<>();
                                map.put("index", i.toString());
                                map.put("ssid", ap.getString("ssid"));
                                map.put("pwd", ap.getString("pwd"));
                                list.add(map);
                                final JSONObject ap_selected = data.getJSONObject(index_of_ap.toString());

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        //listView.setAdapter(adapter);
                                        adapter.notifyDataSetChanged();
                                        try {
                                            txt_ssid.setText(ap_selected.getString("ssid"));
                                            txt_passwd.setText(ap_selected.getString("pwd"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }  // run
                                });
                            }
                        }  // if success
                    }

                    // 可用ap 扫描
                    if (cmd.equals("list_ap")) {
                        // final ListView listView = (ListView) getActivity().findViewById(R.id.list_ap_listview);
                        final ListView listView = new ListView(getContext());

                        final ArrayList<HashMap<String, String>> list = new ArrayList<>();
                        ListAPListviewAdapter adapter = new ListAPListviewAdapter(getActivity(), list);
                        listView.addHeaderView(View.inflate(getContext(), R.layout.list_ap_listview_header, null));
                        listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (position > 0) {
                                    mPosition = position;
                                    view.setSelected(true);
                                }
                            }
                        });

                        Iterator<String> iterator = data.keys();
                        String v;
                        Pattern pattern;
                        Integer i = 0;
                        while (iterator.hasNext()) {
                            v = data.getString(iterator.next());
                            //pattern = Pattern.compile("([^,]+),([^,]+),([^,]+),([^,]*)");
                            pattern = Pattern.compile("([^,]+),([^,]+)");
                            Matcher matcher = pattern.matcher(v);
                            if (matcher.find()) {
                                String s = matcher.group();
                                String[] ss = s.split(",");
                                HashMap<String, String> map = new HashMap<>();
                                map.put("index", i.toString());
                                map.put("ssid", ss[0]);
                                map.put("rssi", ss[1]);
                                list.add(map);
                                i++;
                            }
                        }
                        // update ui
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                                builder.setPositiveButton("选择", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        HashMap<String, String> item = (HashMap<String, String>) listView.getItemAtPosition(mPosition);
                                        txt_ssid.setText(item.get("ssid"));
                                        dialog.dismiss();
                                    }
                                });
                                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.setView(listView);
                                builder.show();
                            }
                        });
                        // outer if
                    }

                    // 写入返回
                    if (cmd.equals("write_wifi")) {
                        final String status = Boolean.toString(data.getBoolean("success"));
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "Wifi写入：" + status, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        sensirion.read_wifi();

        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        //
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    // 扫描可用ap
    public void onListAPClick(View view) {
        sensirion.list_ap();
    }

    interface OnFragmentInteractionListener {
        void onFragmentInteraction(URI uri);
    }

    // end
}
